// 会员
const {userledger,sequelize,merchantInfo,memberInfo} = require('../../dbConfig/index.js')
const { Op } = require('sequelize');
// 注册会员
const registerMember = async (ctx,next) => {
	const body = ctx.request.body
	if(body.user_name){
		const jiance = await userledger.findAll({where:{user_name:body.user_name}})
		if(jiance.length){
			ctx.body = {code:1,data:null,msg:'用户名以被使用'}
			return
		}
	}
	const transaction = await sequelize.transaction();
	const user = await userledger.create({ user_name:body.user_name, user_password:'25d55ad283aa400af464c76d713c07ad',is_flg:'4',creator_id:ctx.state.user_id }, { transaction });
	await memberInfo.create({ 
		user_phone: body.user_phone, 
		full_name:body.full_name,
		user_id: user.Id,
		province:body.province,
		city:body.city,
		county:body.county,
		town:body.town,
		village:body.village,
		province_text:body.province_text,
		city_text:body.city_text,
		county_text:body.county_text,
		town_text:body.town_text,
		village_text:body.village_text,
		member_type:body.member_type.join(','),
		principal_count:body.principal_count,
		principal_num:body.principal_num,
		lines_count:body.lines_count,
		lines_num:body.lines_num,
		head_img:body.head_img
	}, { transaction });
	await transaction.commit();
	ctx.body = {
		code:200,
		data:null,
		msg:"注册成功,密码:12345678,请通知会员尽快修改密码"
	}
}
// 查询会员列表
const getMemberList = async (ctx,next)=>{
	const body = ctx.request.body
	console.log(body,'canshu')
	const user_id = ctx.state.user_id
	const merchant = await userledger.findOne({
		where: { 
		  Id: user_id,
		  is_flg: '2'  // 确保是商家身份
		}
	  });
	  if (!merchant) {
		ctx.body = {
		  code: 400,
		  msg: '商家信息不存在或无权限'
		};
		return;
	  }
	   // 构建查询条件
	   const where = {};
	   if (body.user_phone) {
		 where.user_phone = {
		   [Op.like]: `%${body.user_phone}%`
		 };
	   }
	   if (body.full_name) {
		 where.full_name = {
		   [Op.like]: `%${body.full_name}%`
		 };
	   }
	    // 查询配置
		const queryOptions = {
			where,
			include: [{
			  model: userledger,
			  attributes: ['user_name', 'is_flg', 'creator_id'],
			  where: {
				creator_id: user_id  // 只查询该商家创建的会员
			  },
			  required: true
			}],
			offset: (body.page - 1) * body.size,
			limit: parseInt(body.size),
			order: [['Id', 'DESC']]  // 按 ID 降序排序
		  };
	  
		  // 执行查询
		  const { count, rows } = await memberInfo.findAndCountAll(queryOptions);
		  const formattedRows = rows.map(row => {
			const plain = row.get({ plain: true });
			return {
			  ...plain,
			  user_name: plain.userledger.user_name,
			  is_flg: plain.userledger.is_flg,
			  userledger: undefined  // 移除嵌套数据
			};
		  });
		  ctx.body = {
			  code:200,
			  data:{
				list: formattedRows,
				pagination: {
				  total: count,
				  current: parseInt(body.page),
				  pageSize: parseInt(body.size),
				  totalPages: Math.ceil(count / body.size)
				}
			  },
			  msg:"成功"
		  }
}
// 修改会员信息
const updateMember = async (ctx,next)=>{
	const body = ctx.request.body
	await memberInfo.update({
		user_phone: body.user_phone, 
		full_name:body.full_name,
		province:body.province,
		city:body.city,
		county:body.county,
		town:body.town,
		village:body.village,
		province_text:body.province_text,
		city_text:body.city_text,
		county_text:body.county_text,
		town_text:body.town_text,
		village_text:body.village_text,
		member_type:body.member_type.join(','),
		principal_count:body.principal_count,
		principal_num:body.principal_num,
		lines_count:body.lines_count,
		lines_num:body.lines_num,
		head_img:body.head_img
	},{where:{
		Id:body.Id
	}})
	ctx.body = {
		code:200,
		data:null,
		msg:'成功'
	}
}
const del = async (ctx,next)=>{
	const Id = ctx.request.body
	await memberInfo.destroy({
		where:{
			Id
		}
	})
	ctx.body={
		code:200,
		data:null,
		msg:'成功'
	}
}
// 充值
const recharge = async (ctx,next)=>{
	try {
		const { 
		  Id,  // 会员ID
		  member_type, // 会员类型数组 ['2'] 或 ['3'] 或 ['2','3']
		  principalMoneyCount, // 次卡本金
		  count,              // 次卡额度
		  principalMoney,     // 超划算本金
		  money              // 超划算额度
		} = ctx.request.body
		if(!((principalMoneyCount&&count) || (principalMoney&&money))){
			ctx.body = {
				code: 1,
				msg: '请将信息补充完整'
			  }
			  return
		}
		// 获取当前会员信息
		const member = await memberInfo.findByPk(Id)
		if (!member) {
		  throw new Error('会员不存在')
		}
	
		// 准备更新数据
		const updateData = {}
		
		// 处理次卡充值
		if (member_type.includes('2')) {
		  // 累加次卡本金和额度
		  updateData.principal_count = String(
			Number(member.principal_count || 0) + Number(principalMoneyCount || 0)
		  )
		  updateData.lines_count = String(
			Number(member.lines_count || 0) + Number(count || 0)
		  )
		}
	
		// 处理超划算充值
		if (member_type.includes('3')) {
		  // 累加超划算本金和额度
		  updateData.principal_num = String(
			Number(member.principal_num || 0) + Number(principalMoney || 0)
		  )
		  updateData.lines_num = String(
			Number(member.lines_num || 0) + Number(money || 0)
		  )
		}
	
		// 更新会员类型(如果原来没有的类型，需要添加)
		const currentTypes = member.member_type ? member.member_type.split(',') : []
		const newTypes = [...new Set([...currentTypes, ...member_type])] // 去重
		updateData.member_type = newTypes.join(',')
	
		// 执行更新
		await memberInfo.update(updateData, {
		  where: { Id }
		})
	
		ctx.body = {
		  code: 200,
		  msg: '充值成功'
		}
	
	  } catch (error) {
		console.error('充值失败:', error)
		ctx.status = 500
		ctx.body = {
		  code: 500,
		  msg: '充值失败',
		  error: error.message
		}
	  }
}
module.exports = {
	registerMember,
	getMemberList,
	del,
	updateMember,
	recharge
}